<template>
	<!-- 购物车优惠券 -->
	<view class="container">
		<headTitle title="选择优惠券"></headTitle>
		<view class="content">
			<coupon v-for="(item, index) in couponList" :key="index" :alldata="item" :index="index" @change="changeStatus"></coupon>
			<uniLoadMore :status="loadingType"></uniLoadMore>
		</view>
	</view>
</template>

<script>
import Api from '@/common/api'
import headTitle from '@/components/head-title'
import coupon from '@/components/coupon'
import uniLoadMore from '@/components/uni-load-more/uni-load-more.vue'
export default {
	data() {
		return {
			id: 0, // 商品id
			pageNum: 1,
			couponList: [], // 数组
			loadingType: 'more', //加载更多状态
		}
	},
	onLoad(opt) {
		this.id = opt.parentId
		this.loadData()
	},
	//下拉刷新
	onPullDownRefresh() {
		this.pageNum = 1
		this.loadData('refresh')
	},
	//加载更多
	onReachBottom() {
		this.pageNum += 1
		this.loadData()
	},
	methods: {
		// 获取完优惠券改变状态
		changeStatus(obj) {
			this.couponList[obj.index].couponType = obj.status
		},
		//加载商品 ，带下拉刷新和上滑加载
		async loadData(type = 'add') {
			//没有更多直接返回
			if (type === 'add') {
				if (this.loadingType === 'nomore') {
					return;
				}
				this.loadingType = 'loading'
			} else {
				this.loadingType = 'more'
			}
			
			let obj = {
				pageIndex: this.pageNum,
				pageSize: 10,
			}
			let str = ''
			if(this.id) { // 商品优惠券
				obj.parentId = this.id
				str = Api.coupon.getProductCoupon
			}else { // 购物车优惠券
				str = Api.coupon.getCartCoupon
			}
			
			let list = await Api.apiCall('get', str, obj)
			if (type === 'refresh') {
				setTimeout(() => {
					uni.stopPullDownRefresh()
				}, 1000)
			}
			if(!list) return
			let couponList = list.recordList
			if (type === 'refresh') {
				this.couponList = []
			}
		
			this.couponList = this.couponList.concat(couponList)
		
			//判断是否还有下一页，有是more  没有是nomore
			this.loadingType = list.hasMore ? 'more' : 'nomore'
		},
	},
	components: {
		headTitle,
		coupon,
		uniLoadMore,
	}
}
</script>

<style lang="scss">
page {
	background-color: #F7F7F7;
}
.content {
	padding: 30rpx 20rpx 0;
}
</style>
